package com.me.customerdemo.controller;

import com.me.customerdemo.pojo.User;
import com.me.customerdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Objects;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @GetMapping(value = "/login")
    public ModelAndView loginView() {
        return new ModelAndView("login");
    }

    @PostMapping(value = "/login")
    public ModelAndView login(
            @RequestParam(name = "username", required = true, defaultValue = "") String username,
            @RequestParam(name = "password", required = true, defaultValue = "") String password,
            HttpSession session
    ) {
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.selectByNamePassWord(username, password);

        if (Objects.isNull(user)) {
            modelAndView.setViewName("login");
        }else {
            session.setAttribute("user", user);
            modelAndView.setViewName("redirect:/index");
        }


        return modelAndView;
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session){
        session.removeAttribute("user");
        return new ModelAndView("login");
    }
}
